package it.netsphere.nswing.comp;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import ognl.Ognl;

import org.freixas.jcalendar.DateEvent;
import org.freixas.jcalendar.DateListener;
import org.freixas.jcalendar.JCalendarCombo;

public class NSCalendarCombo
	extends JCalendarCombo
{
	/**
	 *  
	 */
	private static final long serialVersionUID = 4562937251729911736L;

	public NSCalendarCombo()
	{
		super( 
	    		new GregorianCalendar(),
	    		Locale.ITALY,
	    		JCalendarCombo.DISPLAY_DATE | JCalendarCombo.DISPLAY_TIME,
	    		true
	    		);		
		
		setDateFormat(new SimpleDateFormat("dd-MM-yy HH:mm:ss"));
		
		addDateListener( new DateListener()
		{
			@Override
			public void dateChanged(DateEvent ev)
			{
				if(updating)
					return;
				if(getUserObject()==null)
					return;
				if(getUserObjectField()==null)
					return;
				
				try
				{
					Calendar cal = ev.getSelectedDate();
					Ognl.setValue(  getUserObjectField() , getUserObject(),cal.getTime() );
				}
				catch(Exception e)
				{
					throw new RuntimeException( e );
				}
				
			}
		});
		
	}

	private Object userObject;
	public Object getUserObject(){	return userObject;}
	public void setUserObject(Object userObject){	this.userObject = userObject;updateSelectedItem();}
	
	private String userObjectField;
	public String getUserObjectField()	{	return userObjectField;}
	public void setUserObjectField(String userObjectField){	this.userObjectField = userObjectField;updateSelectedItem();}

	private boolean updating=false;
	
	private void updateSelectedItem()
	{
		if(getUserObjectField()==null)
			return;
		if(getUserObject()==null)
			return;
		
		try
		{
			updating = true;
			Date d  = (Date)Ognl.getValue(  getUserObjectField() , getUserObject());
			super.setDate( d );
		}
		catch(Exception e)
		{
			throw new RuntimeException( e );
		}
		finally
		{
			updating = false;
		}
		
	}
	
}
